# dict ----> str
import pickle
import base64

# carts_dict = {'sku_id':[1,True],'sku_id2':[2,False]}
# carts_bytes = pickle.dumps(carts_dict)
# carts_str = base64.b64encode(carts_bytes).decode()
# print(carts_str)

# str -----> dict
# carts_str='gAN9cQAoWAcAAABza3VfaWQycQFdcQIoSwKJZVgGAAAAc2t1X2lkcQNdcQQoSwGIZXUu'
# carts_bytes = base64.b64decode(carts_str.encode())
# carts_dict = pickle.loads(carts_bytes)
from django_redis import get_redis_connection
from rest_framework.response import Response


class ReadWriteTool():
    def read_carts(self, request):
        # 判断用户是否登陆
        if request.user and request.user.is_authenticated:
            return self.read_from_redis(request.user.id)
        else:
            return self.read_from_cookie(request)

    # 从redis中读取数据
    def read_from_redis(self, user_id):
        redis_conn = get_redis_connection('carts')
        carts_str = redis_conn.get('carts_%s' % user_id)
        if not carts_str:
            return {}
        carts_bytes = base64.b64decode(carts_str)
        carts_dict = pickle.loads(carts_bytes)
        return carts_dict

    # 从cooki中读取数据
    def read_from_cookie(self, request):
        carts_str = request.COOKIES.get('carts')
        if not carts_str:
            return {}
        carts_bytes = base64.b64decode(carts_str.encode())
        carts_dict = pickle.loads(carts_bytes)
        return carts_dict

    def write_carts(self, request, response, carts_dict):

        if request.user and request.user.is_authenticated():
            self.write_to_redis(request.user.id, carts_dict)
        else:
            self.write_to_cookie(response, carts_dict)

    # 把数据写入redis
    def write_to_redis(self, user_id, carts_dict):
        redis_conn = get_redis_connection('carts')
        carts_bytes = pickle.dumps(carts_dict)
        carts_str = base64.b64encode(carts_bytes).decode()
        redis_conn.set('carts_%s' % user_id, carts_str)

    # 把数据写入cookie
    def write_to_cookie(self, response, carts_dict):
        carts_bytes = pickle.dumps(carts_dict)
        carts_str = base64.b64encode(carts_bytes).decode()
        response.set_cookie('carts', carts_str, max_age=60 * 60 * 24 * 30)


def mergecarts(user, request, response: Response):
    # user_id = request.user.id  考虑到要在注册的时候就可以合并，request可能取不到user
    user_id = user.id
    tool = ReadWriteTool()
    # 1.取出redis中的购物车数据
    carts_redis = tool.read_from_redis(user_id)
    # 2.取出cookie中的购物车数据
    carts_cookie = tool.read_from_cookie(request)
    # 3.合并
    carts_dict = {}
    carts_dict.update(carts_redis)
    carts_dict.update(carts_cookie)
    # 5.把数据保存到redis中
    tool.write_to_redis(user_id, carts_dict)
    # 4.清楚cookie
    response.delete_cookie('carts')


def merge_cookie_redis(func):
    def wrapper(request, *args, **kwargs):
        print('调用装饰器')
        response = func(request, *args, **kwargs)
        if response.status_code >= 200 and response.status_code <= 300:
            if request.user and request.user.is_authenticated:
                mergecarts(request.user, request, response)
                print('合并购物车成功')
            else:
                raise Exception('非法操作，未找到可操作的用户')
        else:
            print('合并购物车失败')
        return response

    return wrapper
